package com.settlement.system.controller;

import com.settlement.system.csv.CsvExportBuilder;
import com.settlement.system.csv.CsvExportUtil;
import com.settlement.system.common.enums.ExcelFileType;
import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.BasePager;
import com.settlement.system.model.entity.common.SinglePage;
import com.settlement.system.model.entity.common.TblUnificationBillSummary;
import com.settlement.system.model.entity.common.TblWpAuditArchiveRecord;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.IBaseService;
import com.settlement.system.service.ITblRrBillTypeService;
import com.settlement.system.service.ITblUnificationBillSummaryService;
import com.settlement.system.service.csv.DateSpiltCsvDatas;
import com.settlement.system.common.util.common.DictionaryUtil;
import com.settlement.system.common.util.common.FasUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一账单明细汇总 前端控制器
 * @author xiaochuan
 * @since 2021-01-20
 */

@Api(tags = "统一账单明细汇总",description = "统一账单明细汇总")
@Slf4j
@RestController
@RequestMapping("/unification/bill_summary")
public class TblUnificationBillSummaryController extends MergeApiExcelController<TblUnificationBillSummary, Map<String, Object>> {

    @Value("${system.export-root.path}")
    private String exportRootPath;

    @Resource
    private ITblUnificationBillSummaryService tblUnificationBillSummaryService;

    @Resource
    private ITblRrBillTypeService tblRrBillTypeService;

    @Resource
    private DictionaryUtil dictionaryUtil;

    @Override
    public IBaseService init() {
        return tblUnificationBillSummaryService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblUnificationBillSummary.class;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model,
                "shopNo","channelNo","editorName","companyNo",
                "summaryId","accountStatus","shareStatus","billCategory",
                "recordAccountProject","nameShort","billType"
        );
        super.setParamsModel(model);
    }

    @Override
    protected void setFootModel(Map<String, Object> result, Map<String, Object> model) throws ServiceException {
        result.put("foot", tblUnificationBillSummaryService.getFoot(model));
    }

    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> params = buildParam(request);
        setParamsModel(params);
        Object fileName = "RR-统一账单汇总";
        String path = exportRootPath + System.currentTimeMillis() + File.separator;
        CsvExportUtil.createCsv()
                .headClass(TblUnificationBillSummary.class)
                .fileName(fileName.toString())
                .fileType(ExcelFileType.XLSX)
                .model(CsvExportBuilder.MULTI_ZIP_MODEL)
                .parentPath(path)
                .csvDatas(new DateSpiltCsvDatas(tblUnificationBillSummaryService, params))
                .export(request, response);
    }

    @Override
    protected ObjectDataResponse batchDelete(@RequestBody List<TblUnificationBillSummary> deleteList, HttpServletRequest request) {
        try {
            String message = tblUnificationBillSummaryService.checkBeforeDelete(deleteList);
            if (StringUtils.isEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            } else {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), message);
            }
        } catch (Exception ex) {
            log.info("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }

    @ApiOperation("生成NC凭证")
    @RequestMapping(value = "produceNc", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse produceNc(@RequestBody Map<String, Object> model, HttpServletRequest request) {
        try {
            setParamsModel(model);
            String message = tblUnificationBillSummaryService.produceNc(model);
            if (StringUtils.isEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            } else {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), message);
            }
        } catch (Exception ex) {
            log.info("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }

    @ApiOperation("撤销NC")
    @RequestMapping(value = "revokeNc", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse revokeNc(@RequestBody Map<String, Object> model, HttpServletRequest request) {
        try {
            setParamsModel(model);
            String message = tblUnificationBillSummaryService.revokeNc(model);
            if (org.springframework.util.StringUtils.isEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            } else {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), message);
            }
        } catch (Exception ex) {
            log.info("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }

    @Override
    protected ObjectDataResponse getPageList(HttpServletRequest request, @RequestBody BasePager<Map<String, Object>> model) throws ServiceException {
        Map<String, Object> result = new HashMap<>(16);
        try {
            insetMenuMemory(model.getModel());
            processModel(model);
            setParamsModel(model.getModel());
            int count = baseService.selectCount(model.getModel());
            List<TblUnificationBillSummary> rows = baseService.selectByPage(new SinglePage(model), model.getModel(),
                    model.getOrderByField(), model.getOrderBy());
//            formatData(rows);
            result.put("rows", rows);
            result.put("total", count);
            setFootModel(result, model.getModel());
        } catch (Exception ex) {
            throw new ServiceException("获取列表出错",ex);
        }
        return new ObjectDataResponse<Map>(result, 200, "获取列表成功");
    }

    @ApiOperation("费用分摊前的校验")
    @RequestMapping(value = "checkBeforeCostShare", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse checkBeforeCostShare(HttpServletRequest request, @RequestBody Map<String, Object> model) throws ServiceException {
        Map<String, Object> result = new HashMap<>(16);
        TblWpAuditArchiveRecord record = null;
        try {
            setParamsModel(model);
            String message = tblUnificationBillSummaryService.checkBeforeCostShare(model);
            if (StringUtils.isNotEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
            }
            return new ObjectDataResponse<Map>(result, 200, "获取列表成功");
        } catch (Exception ex) {
            log.error("获取列表出错", ex);
            throw new ServiceException("获取列表失败，请联系管理员！",ex);
        }
    }

    @ApiOperation("费用分摊")
    @RequestMapping(value = "costShare", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse costShare(@RequestBody Map<String, Object> model, HttpServletRequest request) {
        try {
            String nameShort = dictionaryUtil.getNameShortShowChildBrandName();
            if(StringUtils.isNotEmpty(nameShort)){
                model.put("nameShort",nameShort);
            }

            setParamsModel(model);
            String message = tblUnificationBillSummaryService.costShare(model);
            if (StringUtils.isEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            } else {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), message);
            }
        } catch (Exception ex) {
            log.info("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }

}

